package com.example.my_rabbitmq_high_demo.api.ttl;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;

/**
 * @Description: 消费者，设置队列过期时间
 * @Author: GaoJian
 * @Date: 2022/7/9 17:53
 */
public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1、创建连接工厂并设置属性
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setVirtualHost("/");

        //2、创建连接
        Connection connection = factory.newConnection();

        //3、使用connection创建channel
        Channel channel = connection.createChannel();

        //4、声明（创建）一个队列
        String queueName = "test_ttl_queue";

        HashMap<String, Object> arguments = new HashMap<>();
        //设置队列超时时间
        arguments.put("x-message-ttl", 10000);
        channel.queueDeclare(queueName, true, false, false, arguments);

        //5、创建消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);

        //6、设置channel
        channel.basicConsume(queueName, true, consumer);
        while (true) {
            //7、获取消息
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            System.out.println(new String(delivery.getBody()));
            //获取header中的内容
            System.out.println(delivery.getProperties().getHeaders().get("name"));
        }
    }
}
